package arch.coal.ellipse.security.utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * Class is used to print a log file based on information
 * provided in a property file.
 * @author mblackford
 *
 */
public class FileLogger {

	private static BufferedWriter out;
	static Logger logger = Logger.getLogger(FileLogger.class);
	
	static {
		
		//Generate a log file based on the information provided in the 
		//properties file.
		String fileName = null;
		try {
			fileName = StaticInfo.properties.getProperty("out.file.path.name");
			if(fileName == null) {
				throw new Throwable("Need a file name");
			}
		} catch(Throwable t) {
			logger.warn(" Using default file name");
			fileName = "defaultFile.txt";
		}

		try {
			out = new BufferedWriter(new FileWriter(fileName));
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public static void newLog(String logName) {
		
		logger.debug("Attempting to change the logging location.");
		//Generate a log file based on the information passed in 
		String fileName = logName;
		try {
			if(fileName == null) {
				throw new Throwable("Need a file name");
			}
		} catch(Throwable t) {
			logger.warn(" Using default file name");
			fileName = "defaultFile.txt";
		}

		try {
			out = new BufferedWriter(new FileWriter(fileName));
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}

/**
 * Method will write to the log the value of the String passed in.
 * @param inString
 */	
	public static void write(String inString) {
		
		try {
			out.write(inString);
		} catch (IOException e) {
			logger.error(" ***** IO EXCEPTION *****");
		} 
	}
	
	public static void close() throws IOException {
		try {
			logger.debug("- closing");
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}finally {
			;
		}
	}
	
	/**
	 * Makes sure the log is properly closed out, that all resources are 
	 * returned to the system.
	 */
	protected void finalize() throws Throwable {
		try {
			logger.debug("- closing");
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}finally {
			super.finalize();
		}
	}

}
